package me.zxk.qwert_poetry.service;

import me.zxk.qwert_poetry.dao.Author;
import me.zxk.qwert_poetry.dao.AuthorRepository;
import me.zxk.qwert_poetry.util.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
public class AuthorServiceImpl implements AuthorService{
    private final int ERR_AUTHOR_NOT_FOUND = 1000;

    @Autowired
    private AuthorRepository authorRepository;

    @Override
    public Author getAuthorById(int id) {
        return authorRepository.findById(id).orElseThrow(() -> new ApiException("作者 ID 不存在", ERR_AUTHOR_NOT_FOUND));
    }

    @Override
    public Author getAuthorByName(String name) {
        return authorRepository.findByName(name).orElse(null);
    }

    @Override
    public Author addAuthor(Author author) {
        return authorRepository.save(author);
    }

    @Override
    public Author deleteAuthorById(int id) {
        Author author = authorRepository.findById(id).orElse(null);
        if (author != null) {
            authorRepository.deleteById(id);
        } else {
            throw new ApiException("作者 ID 不存在", ERR_AUTHOR_NOT_FOUND);
        }
        return author;
    }

    @Override
    public Author updateAuthor(Author author) {
        Author authorInDb = authorRepository.findById(author.getId()).orElse(null);
        if (authorInDb != null) {
            authorInDb.setName(author.getName());
            authorInDb.setDynasty(author.getDynasty());
            authorInDb.setDesc(author.getDesc());
            authorRepository.save(authorInDb);
        } else {
            throw new ApiException("作者 ID 不存在", ERR_AUTHOR_NOT_FOUND);
        }
        return author;
    }

    @Override
    public Page<Author> listAuthors(int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return authorRepository.findAll(pageable);
    }

}
